<?php
class Rcp_LpImport_EmployeeImport_Users {
	
	/**
	 * Tablica obiektów RcpUsers gdzie klucz to ExtId (LogoId z bazy LP)
	 * @var RcpUsers[]
	 */
	private $_map = array();
	
	public function __construct() {
		$this->_map = RcpUsersQuery::create()
			->useUserRolesQuery(null, Criteria::LEFT_JOIN)
				->leftJoinRoles()
			->endUse()
			->leftJoinPositions()
			->leftJoinUnits()
			->leftJoinUserCalendars()
			->with('Positions')
			->with('Units')
			->with('UserRoles')
			->with('UserCalendars')
			->find()
			->getArrayCopy('ExtId');
	}
	
	/**
	 * @param LpEmployees $lpEmployee
	 * @return RcpUsers
	 */
	private function _add(LpEmployees $lpEmployee) {
		$extId = $lpEmployee->getLogoId();
		$user = new RcpUsers();
		$user->setExtId($extId);
		$user->setActive(true);
		$this->_map[$extId] = $user;
		return $user;
	}
	
	/**
	 * @param LpEmployees $lpEmployee
	 * @return RcpUsers
	 */
	private function _getWithAdd(LpEmployees $lpEmployee) {
		$user = $this->get($lpEmployee->getLogoId());
		if (!($user instanceof RcpUsers))
			$user = $this->_add($lpEmployee);
		return $user;
	}
	
	/**
	 * @param string $extId
	 * @return RcpUsers|NULL
	 */
	public function get($extId) {
		if (key_exists($extId, $this->_map))
			return $this->_map[$extId];
		return null;
	}
	
	/**
	 * @param LpEmployees $lpEmployee
	 * @return RcpUsers
	 */
	public function update(LpEmployees $lpEmployee) {
		$user = $this->_getWithAdd($lpEmployee);
		$user->setFname($lpEmployee->getFname());
		$user->setLname($lpEmployee->getLname());
		$user->setEmail($this->_generateEmail($lpEmployee));
		$user->setPassword(hash('sha256', 'vgp'));
		return $user;
	}
	
	private function _generateEmail(LpEmployees $lpEmployee) {
		return strtolower($lpEmployee->getFname()) . '.' . strtolower($lpEmployee->getLname()) . '@vw-group.pl';
	}
	
}